<template>
  <div class="app-container">
      <el-alert    title="请先选择学期、班级、考试和课程"    type="success"> </el-alert>
      <br />
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="sem_id">
        <el-select
          v-model="queryParams.sem_id"
          placeholder="请选择"
          clearable
          filterable @change="changeSemester"
        >
          <el-option
            v-for="dict in semesterOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="class_id">
        <el-select
          v-model="queryParams.class_id"
          placeholder="请选择"
          clearable
          filterable @change="loadStudent"
        >
          <el-option
            v-for="dict in classOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试" prop="exam_id">
        <el-select
          v-model="queryParams.exam_id"
          placeholder="请选择"
          clearable
          filterable @change="changeExam"
        >
          <el-option
            v-for="dict in examOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程" prop="course_id">
        <el-select
          v-model="queryParams.course_id"
          placeholder="请选择"
          clearable
          filterable @change="changeCourse"
        >
          <el-option
            v-for="dict in courseOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
              v-hasPermi="['teach:result:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teach:result:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="student_num" />
      <el-table-column label="姓名" align="center" prop="student_name" />
      <el-table-column label="分数" align="center" prop="score">
          <template slot-scope="scope">              
            <el-input-number v-model="scope.row.score" placeholder="请输入分数" @change="changeScore(scope.row)" v-if="semId == scope.row.sem_id"/>
            <span v-else>{{ scope.row.score }}</span>
          </template>
      </el-table-column>
      <el-table-column label="等级" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.result_level" :value="scope.row.level"/>
        </template>
      </el-table-column>
    </el-table>

    <import-dialog :open="upload" model="teach_result" @cancel="importCancel" @success="importSuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ImportDialog from "@/components/ImportDialog";

export default {
  name: "Result",
  components: {
    ImportDialog
  },
  dicts: ['result_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试成绩表格数据
      resultList: [],
      semesterOptions: [],
      classOptions: [],
      courseOptions: [],
      examOptions: [],
      studentOptions: [],
      semId: null,
      semName: null,
      className: null,
      courseName: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        sem_id: null,
        class_id: null,
        course_id: null,
        student_id: null,
        student_name: null,
        level: null,
        exam_id: null,
        "@table": "teach_result",
        "@exp": {

        }
      },
      pager: {
        page: 1,
        limit: 200,
        order: "id desc",
      },
      // 导入参数
      upload: false
    };
  },
  created() {
    this.getList();
    this.initOptions();
  },
  methods: {
    /** 查询考试成绩列表 */
    getList() {
        if(!this.queryParams.sem_id || !this.queryParams.class_id || !this.queryParams.exam_id || !this.queryParams.course_id){
            this.loading = false;
            return;
        }
      this.loading = true;
      let params = {"@pager": this.pager, ...this.queryParams};
      apiGet(params).then(response => {
        this.resultList = response.data.rows;
        this.total = response.data.total;
        this.initStudents();
        this.loading = false;
      });
    },
    initOptions() { 
      
      apiGet({ "@table": "base_semester", status: "1", "@pager": { page: 1, limit: 100 }, }).then((response) => {
        this.semesterOptions = response.data.rows;
            for (let i = 0; i < this.semesterOptions.length; i++) {
              if (this.semesterOptions[i]["is_current"] == "Y") {
                this.queryParams.sem_id = this.semesterOptions[i].id;
                this.semName = this.semesterOptions[i].name;
                this.semId = this.semesterOptions[i].id;
              }
            }
      });

      apiDs("base_class_result_import").then((response) => {
        this.classOptions = response.data;
      });
      apiDs("base_course_result_import").then((response) => {
        this.courseOptions = response.data;
      });

      apiGet({ "@table": "teach_exam", status: "1", "@pager": { page: 1, limit: 100 }, }).then((response) => {
        this.examOptions = response.data.rows;
      });

    },
    loadStudent() {
      apiGet({ "@table": "base_student", "class_id": this.queryParams.class_id, status: "1", "@pager": { page: 1, limit: 100 }, }).then((response) => {
        this.studentOptions = response.data.rows;
      });
      for(let i=0;i<this.classOptions.length;i++){
          if(this.classOptions[i].value == this.queryParams.class_id){
              this.className = this.classOptions[i].name;
          }
      }
    },
    initStudents() {
        if(this.resultList == null){
            this.resultList = [];
        }
        for(let i=0;i<this.studentOptions.length;i++){
            let s = this.studentOptions[i];
            let row = null;
            for(let j=0;j<this.resultList.length;j++){
                if(this.resultList[j]['student_id'] == s.id){
                    row = this.resultList[i];
                }
            }
            if(row == null){
                row = {
                    id: null,
                    sem_id: this.queryParams.sem_id,
                    sem_name: this.semName,
                    class_id: this.queryParams.class_id,
                    class_name: this.className,
                    course_id: this.queryParams.course_id,
                    course_name: this.courseName,
                    student_id: s.id,
                    student_name: s.name,
                    student_num: s.num,
                    score: null,
                    level: null,
                    exam_id: this.queryParams.exam_id,
                    exam_name: this.examName
                };
                this.resultList.push(row);
            }
        }
    },
    changeCourse() {
      for(let i=0;i<this.courseOptions.length;i++){
          if(this.courseOptions[i].value == this.queryParams.course_id){
              this.courseName = this.courseOptions[i].label;
          }
      }
    },
    changeExam() {
      for(let i=0;i<this.examOptions.length;i++){
          if(this.examOptions[i].id == this.queryParams.exam_id){
              this.examName = this.examOptions[i].name;
          }
      }
    },
    changeSemester() {
      for(let i=0;i<this.semesterOptions.length;i++){
          if(this.semesterOptions[i].id == this.queryParams.sem_id){
              this.semName = this.semesterOptions[i].name;
          }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    changeScore(row) {
      let data = {
          'teach_result': row,
           '@tags': ['teach_result']
         };
        if (row.id != null) {
            apiPut(data).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
            }).catch(err=>{
                row.score = null;
            });
        } else {
            apiPost(data).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
            }).catch(err=>{
                row.score = null;
            });
        }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的考试成绩数据？').then(function() {
        let data = {};
        data['teach_result'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['teach_result'];
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload = true;
    },
    importSuccess(msg) {
        this.upload = false;
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    importCancel() {
        this.upload = false;
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['teach_result'] = {...this.queryParams};
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    }
  }
};
</script>
